// concurrentworker.h
#ifndef CONCURRENTWORKER_H
#define CONCURRENTWORKER_H

#include <QObject>
#include <QtConcurrent>
#include <QFutureWatcher>
#include <QDebug>
#include <QThread>
#include <QRandomGenerator>
#include <QDateTime>
#include <ConcurrentPipeline.h>
/// 后台并发工作类，使用 QtConcurrent 运行任务
class ConcurrentWorker : public QObject
{
    Q_OBJECT

public:
    explicit ConcurrentWorker(QObject *parent = nullptr)
        : QObject(parent),
        m_running(false),
        m_interval(20),
        m_itemCount(5)    { //1s 6次 每次25个数据  共 150点  每次3个点 一秒获取50次  每次20ms

        m_pipeline = new ConcurrentPipeline<int>();
        // 连接完成信号
        connect(&m_watcher, &QFutureWatcher<void>::finished,
                this, &ConcurrentWorker::onFinished);
    }

    ~ConcurrentWorker() {
        stop();
    }

    void clear(){
        m_pipeline->clear();
    }
    void pushPoint(const QList<int> &items){

        if (m_pipeline->size() > m_pipeline->getMaxSize() ) {
            qWarning() << "队列已满，丢弃数据，当前大小:" << m_pipeline->size();
            return;
        }
        QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>();
        connect(watcher, &QFutureWatcher<bool>::finished, [watcher]() {
            watcher->deleteLater();  // 任务完成后自动删除
        });
        // 使用 QtConcurrent 在后台推送，避免阻塞UI线程
        QFuture<bool> pushFuture = QtConcurrent::run([this, items]() {
            return this->m_pipeline->pushBatch(items);
        });
        watcher->setFuture(pushFuture);
    }
    // 带回调的推送版本
    void pushPointWithCallback(const QList<int> &items,
                               std::function<void(bool success)> callback = nullptr) {

        QFuture<bool> pushFuture = QtConcurrent::run([this, items]() {
            return this->m_pipeline->pushBatch(items);
        });
        // 如果需要回调，使用 QFutureWatcher
        if (callback) {
            QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>();
            watcher->setFuture(pushFuture);
            // 使用 lambda 捕获 watcher，完成后自动删除
            connect(watcher, &QFutureWatcher<bool>::finished, [watcher, callback]() {
                bool success = watcher->result();
                callback(success);
                watcher->deleteLater();  // 正确：删除局部变量
            });
        }
    }
public slots:
    void start(int interval = 20) {
        if (m_running) {
            qDebug() << "Worker 已经在运行";
            return;
        }
        m_running = true;
        m_interval = interval;
        qDebug() << "启动后台任务，间隔:" << interval << "ms, 线程:" << QThread::currentThread();

        // 使用 QtConcurrent 在后台线程运行
        m_future = QtConcurrent::run([this]() {
            this->run();
        });
        //m_future = QtConcurrent::run(std::bind(&ConcurrentWorker::run, this));
        m_watcher.setFuture(m_future);
        emit started();
    }
    void stop() {
        if (!m_running) return;

        qDebug() << "停止后台任务";
        m_running = false;

        if (m_future.isRunning()) {
            m_future.waitForFinished(); // 等待任务完成
        }

    }

    void setInterval(int interval) {
        m_interval = interval;
        qDebug() << "设置间隔:" << interval << "ms";
    }

    void setItemCount(int count ){
        m_itemCount = count;
    }

    bool isRunning() const {
        return m_running;
    }

//槽函数
private slots:
    void onFinished() {
        qDebug() << "后台任务完成";
        emit stopped();
    }

private:
    void run() {
        qDebug() << "后台任务开始执行，线程:" << QThread::currentThread();
        while (m_running) {
            // 模拟工作 - 生成数据

            QList<int> data = m_pipeline->popBatch(m_itemCount); // 超时100ms
            if (data.isEmpty()) {
                continue; // 没有数据，继续循环
            }
            // 使用 invokeMethod 确保信号在正确的线程中发射
            emit dataProduced(data);
            // 等待指定间隔
            QThread::msleep(m_interval);
        }
        qDebug() << "后台任务退出循环";
    }
    //信号函数
signals:
    void started();
    void stopped();
    void dataProduced(const QList<int> &data);

private:
    bool m_running;
    int m_interval;
    int m_itemCount;
    QFuture<void> m_future;
    QFutureWatcher<void> m_watcher;
    ConcurrentPipeline<int>* m_pipeline = nullptr;
};

#endif // CONCURRENTWORKER_H
